import { app, BrowserWindow, globalShortcut} from "electron"
import path, { join } from "path"
import checkUpdate from "../check-update"

let win: BrowserWindow | null

const createWindow = () => {
  win = new BrowserWindow({
    width: 540,
    height: 990,
    backgroundColor: '#f4f4ff',
    show: false,
    // frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, '../preload/index.js'),
    },
  })
  // 视图宽高比
  win.setAspectRatio(6/11)

  if (!app.isPackaged) {
    win.loadURL(`http://localhost:${process.env.VITE_DEV_SERVER_PORT}`)
    win.webContents.openDevTools()
  } else {
    win.loadFile(join(__dirname, `../../index.html`))
  }

  globalShortcut.register('CommandOrControl+Shift+i', () => {
    if (!win) return
    win.webContents.openDevTools()
  })

  win.webContents.session.webRequest.onHeadersReceived((details: any, callback: any) => {
    callback({ responseHeaders: Object.fromEntries(Object.entries(details.responseHeaders).filter(header => !/x-frame-options|content-security-policy/i.test(header[0]))) });
  })

  // 优雅的展示窗口
  win.once("ready-to-show", () => {
    win?.show()
    win?.webContents.send('get-exe-path', app.getPath('exe'))
    // 打包后的应用才检查版本更新
		if (app.isPackaged && win) {
			checkUpdate(win)
		}
  })

  // createWorkerWindow()

  win.on('closed', () => {
    win = null
    // if (workerWin) {
    //   workerWin.close()
    // }
  })

  return win
}

export const useMain = () => {
  if (win) return win
  return createWindow()
}